<template>
    <div id="movie-manage">
      <!--搜索-->
      <div class="top">
        <el-col :span="12">
          <el-input placeholder="请输入内容" v-model="input" class="input-with-select" style="width: 100%">
            <el-button slot="append" icon="el-icon-search" @click="search">搜索</el-button>
          </el-input>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-button type="primary" size="small" @click="addMovie">添加电影</el-button>
        </el-col>
      </div>
      <!--表格-->
      <div class="movie-table">
        <el-table
          border
          :data="tableData">
          <el-table-column label="电影 ID" align="center" width="100" prop="id"></el-table-column>
          <el-table-column label="电影名" show-overflow-tooltip prop="filmName"></el-table-column>
          <el-table-column label="导演" width="100" align="center" show-overflow-tooltip prop="director">
          </el-table-column>
          <!-- <el-table-column
            label="主演"
            prop="actor">
          </el-table-column> -->
          <el-table-column label="类型"  align="center"  width="100"  prop="type"></el-table-column>
          <el-table-column  align="center"  label="上映时间"  prop="releaseTime"></el-table-column>
          <el-table-column   width="200"  align="center"  label="操作">
            <template slot-scope="scope">
              <el-button  size="mini"  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button  size="mini"  type="danger"   @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="block" v-if="tableData.length">
        <el-pagination
          @current-change="currentChange"
          background
          layout="prev, pager, next"
          :page-size="6"
          :total="total">
        </el-pagination>
      </div>
      <!--弹框-->
      <div>
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogFormVisible"
          :modal-append-to-body="false"
          v-if="dialogFormVisible"
          :showClose="false"
        >
          <el-form :label-position="labelPosition" :rules="rules" label-width="80px" :model="movieInfo">
            <el-form-item label="电影名" prop="filmName">
              <el-col :span="16">
                <el-input v-model="movieInfo.filmName"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="海报" prop="poster">
              <el-col :span="16">
                <img :src="movieInfo.poster" ref="previewImg" alt="" width="150px" height="200px">
                <div style="position: relative;height: 64px">
                  <el-button size="small" type="primary" style="position: absolute;left: 0;top: 0;cursor: pointer">点击上传</el-button>
                  <input type="file" id="file" name="file" ref="uploadImg" accept="image/png, image/jpeg, image/gif, image/jpg"
                   style="position: absolute;left: 0;top: 0;opacity: 0;height: 32px;width: 80px;cursor: pointer" @change="changeImg">
                  <div slot="tip" class="el-upload__tip" style="position: absolute;left: 0;top: 32px;height: 32px">只能上传jpg/png文件，且不超过500kb</div>
                </div>
              </el-col>
            </el-form-item>
            <el-form-item label="导演" prop="director">
              <el-col :span="16">
                <el-input v-model="movieInfo.director"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="演员" prop="leadingRole">
              <el-col :span="16">
                <el-input v-model="movieInfo.leadingRole"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="片长" prop="duration">
              <el-col :span="16">
                <el-input v-model="movieInfo.duration"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="语言" prop="language">
              <el-col :span="16">
                <el-select v-model="movieInfo.language" placeholder="请选择语言" style="width: 100%">
                  <el-option
                    v-for="item in languageOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-col :span="16">
                <el-select v-model="movieInfo.type" placeholder="请选择类型" style="width: 100%">
                  <el-option
                    v-for="item in typeOptions"
                    :key="item.tagId"
                    :label="item.value"
                    :value="item.tagId">
                  </el-option>
                </el-select>
              </el-col>
            </el-form-item>
            <el-form-item label="上映时间" prop="releaseTime">
              <el-col :span="16">
                <el-date-picker type="date" placeholder="选择日期" v-model="movieInfo.releaseTime" style="width: 100%;"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="简介" prop="introduction">
              <el-col :span="16">
                <el-input type="textarea" v-model="movieInfo.introduction" :autosize="{ minRows: 8, maxRows: 10}"></el-input>
              </el-col>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="manageMovieInfo()">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
</template>

<script>
    import {upLoadImg,getTags,getCurrentPageMovie,addMovieInfo,updateMovieInfo,deleteMovieInfo} from '../../../api/index'
    import {MessageBox,Message} from 'element-ui'
    export default {
        name: "MovieManage",
        data() {
          let checkMovieLong = (rule, value, callback) => {
            if (!value) {
              callback(new Error('片长信息不能为空'));
            } else {
              if (/^[1-9]{1}[0-9]{1,2}$/.test(value)){
                callback();
              } else{
                callback(new Error('请输入纯数字'));
              }
            }
          };
          return {
            //服务器地址
           // server:'http://localhost:3000',
            tableData:[],
            total:0,
            pageSize:6,
            currentPage:1,
            movieInfo:{},
            posterURL:"",
            dialogFormVisible:false,
            dialogTitle:'',
            labelPosition:'right',
            input:'',
            searchInput:'',
            checkMovieLongFlag:false,
            rules:{
              filmName: [
                { required: true, message: '电影名不能为空', trigger: 'blur' },
              ],
              poster: [
                { required: true, message: '请上传电影海报', trigger: 'blur' },
              ],
              director: [
                { required: true, message: '导演信息不能为空', trigger: 'blur' },
              ],
              leadingRole: [
                { required: true, message: '主演信息不能为空', trigger: 'blur' },
              ],
              duration: [
                { required: true, message: '片长信息不能为空', trigger: 'blur' },
                { validator: checkMovieLong, trigger: 'blur' }
              ],
              language: [
                { required: true, message: '请选择语言', trigger: 'change' },
              ],
              type: [
                { required: true, message: '请选择电影类型', trigger: 'change' },
              ],
              public_date: [
                { required: true, message: '请选择上映日期', trigger: 'blur' },
              ],
              intro: [
                { required: true, message: '电影简介信息不能为空', trigger: 'blur' },
              ]
            },
            languageOptions: [{
              value: '粤语',
              label: '粤语'
            }, {
              value: '国语',
              label: '国语'
            }, {
              value: '英语',
              label: '英语'
            }, {
              value: '日语',
              label: '日语'
            }, {
              value: '其它',
              label: '其它'
            }],
            typeOptions:[],
            pickerPublicDate: {
              disabledDate(time) {
                return time.getTime() < Date.now();
              },
            }
          }
        },
        created(){
          this.loadCurrentPageMovie(this.currentPage,this.pageSize,'');
          this.loadTags();
        },
        methods: {
          async loadTags(){
            let json = await getTags();
            if(json.code === 0 ){
              this.typeOptions = json.data;
            }
            //console.log(this.typeOptions);
          },
          async loadCurrentPageMovie(currentPage,pageSize,input){
            let json = await getCurrentPageMovie(currentPage,pageSize,input);
            if (json.code===0){
              this.tableData = json.data.records;
              //console.log(json.data.records);
              this.getFilmType(this.tableData)
              this.total = json.data.total;
            }
          },
          async currentChange(currentPage){
            this.currentPage = currentPage;
            this.loadCurrentPageMovie(this.currentPage,this.pageSize,this.searchInput);
          },
         async handleEdit(index, row) {
            this.dialogTitle = '编辑电影信息';
            this.movieInfo = row;
           // console.log(row);
            this.dialogFormVisible = true;
            // console.log(index, row);
          },
          async handleDelete(index, row) {
            console.log(index, row);
            MessageBox.confirm('此操作将永久删除该电影所有信息, 是否继续？','提示').then(async (value)=>{
              if (value==='confirm'){
                let json = await deleteMovieInfo(row.id);
                if (json.code===0){
                  this.loadCurrentPageMovie(this.currentPage,this.pageSize,this.searchInput);
                  Message.success('删除该电影成功！');
                }
              }
            });
          },
          //图片上传
          async changeImg(e){
             let formData = new FormData();
            formData.append("file", this.$refs.uploadImg.files[0]);
            let json = await upLoadImg(formData);
            console.log(json);
            if(json.code === 0){
             
              let reader = new FileReader();
              reader.readAsDataURL(this.$refs.uploadImg.files[0]);//发起异步请求
              let _this = this;
              reader.onload = function(){
                //读取完成后，将结果赋值给img的src
                _this.$refs.previewImg.src = this.result;
               // _this.movieInfo.poster = this.result;
              }
               if (json.data.length){
                  this.movieInfo.poster = "http://oopswj.xyz:8000/img/" +json.data;
                }
            }
          },
          //修改电影信息
          async manageMovieInfo(){
            console.log(this.movieInfo.type);
            if (this.movieInfo.filmName&&
            this.movieInfo.poster&&
            this.movieInfo.director&&
            this.movieInfo.leadingRole&&
            this.movieInfo.duration&&
            (/^[1-9]{1}[0-9]{1,2}$/).test(this.movieInfo.duration)&&
            this.movieInfo.type&&
            this.movieInfo.language&&
            this.movieInfo.releaseTime&&
            this.movieInfo.introduction) {
        
                let json;
                if (this.movieInfo.releaseTime) {
                  let date = new Date(this.movieInfo.releaseTime);
                  this.movieInfo.releaseTime = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
                 // this.movieInfo.releaseTime = date;
                }
                this.typeOptions.forEach((item,index)=>{
                    console.log(item);
                    if(item.value === this.movieInfo.type){
                      this.movieInfo.type = item.tagId;
                    }
                });
                //console.log(this.movieInfo.type);
                
                if (this.dialogTitle === '编辑电影信息') {
                  console.log(this.movieInfo.poster);
                  json = await updateMovieInfo(this.movieInfo.id,this.movieInfo.filmName,this.movieInfo.poster,this.movieInfo.director,
                                              this.movieInfo.leadingRole,this.movieInfo.duration,this.movieInfo.type,
                                              this.movieInfo.language,this.movieInfo.releaseTime,this.movieInfo.introduction);
                  if (json.code===0){
                    this.dialogFormVisible = false;
                    Message.success('修改电影信息成功！');
                  } else{
                    Message.error(json.msg);
                  }
                } else{
                  json = await addMovieInfo(this.movieInfo.filmName,this.movieInfo.poster,this.movieInfo.director,
                                              this.movieInfo.leadingRole,this.movieInfo.duration,this.movieInfo.type,
                                              this.movieInfo.language,this.movieInfo.releaseTime,this.movieInfo.introduction);
                  if (json.code===0){
                    this.loadCurrentPageMovie(this.currentPage,this.pageSize,this.searchInput);
                    this.dialogFormVisible = false;
                    Message.success('添加电影成功！');
                  } else {
                    Message.error(json.msg);
                  }
                } 
              this.loadCurrentPageMovie(this.currentPage,this.pageSize,this.searchInput);
            } else{
              Message.error('请完成必填内容！');
            }
          },
          //搜索电影
          search(){
            this.searchInput = this.input;
            this.loadCurrentPageMovie(1,this.pageSize,this.searchInput);
          },
          //添加电影
          addMovie(){
            this.dialogTitle = '添加电影';
            this.movieInfo = {};
            this.dialogFormVisible = true;
          },
          cancel(){
            this.dialogFormVisible = false;
            this.loadCurrentPageMovie(this.currentPage,this.pageSize,this.searchInput);
          },
          async getFilmType(movieList){
          movieList.forEach((item,index)=>{
            if(item.tags.length !=0){
              let type ='';
              item.tags.forEach((tag,index)=>{
                type =type+tag.value +","
              })
              //为对象添加新值
              this.$set(item,"type",type.substring(0, type.length - 1));
            }
          })  
        }
        },
    }
</script>

<style>
  .movie-table{
    width:90%;
    min-width:900px;
    margin: 0 auto;
    margin-bottom: 30px;
  }
  .top{
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 30px 0;
    margin-bottom: 30px;
  }
  .block{
    text-align: center;
  }
  .el-dialog__header{
    text-align: center;
  }
  .el-dialog__body .el-form-item{
    padding-left: 20%;
  }
</style>
